<template>
    <ZljHeader msg="机构指标映射"></ZljHeader>
    <el-container style="background-color: #f5f7fa;padding:0 ;">
        <el-main style="margin:1rem 1rem 0 1rem;background-color: rgb(255, 255, 255);">
            <div class="pick">
                <p style="font-size: 0.5rem; padding-left:1rem;">数据筛选</p>
                <div class="pick-form">
                    <div>
                        <el-form :inline="true" :model="searchValue" class="demo-form-inline">
                            <el-form-item label="输入查询：">
                                <el-input v-model="searchValue.inOrganName" placeholder="指标名称:" clearable />
                            </el-form-item>

                            <el-form-item label="体验机构：">
                                <el-select v-model="searchValue.organId" placeholder="全部" @change="selectClick" clearable>
                                    <el-option v-for="item in itemArr" :key="item" :value="item.organId"
                                        :label="item.organName" class="input-wh" />
                                </el-select>
                            </el-form-item>

                            <el-form-item label="指标映射状态：">
                                <el-select v-model="searchValue.type" placeholder="全部" clearable>
                                    <el-option label="未匹配" value="未匹配" />
                                    <el-option label="已匹配" value="beijing" />
                                </el-select>
                            </el-form-item>
                        </el-form>
                    </div>
                    <div>
                        <el-form-item>
                            <el-button type="primary" @click="onSubmit" :v-model="searchValueArr">查询</el-button>
                            <el-button @click="onReset">重置</el-button>
                        </el-form-item>
                    </div>
                </div>
            </div>
            <div class="pick-btn">
                <el-button @click="dialogFormVisible = true">添加</el-button>
                <el-button @click="delLot">删除</el-button>
                <el-button>导入</el-button>
            </div>
            <!-- 表格 -->
            <div class="pick-table">
                <el-table ref="multipleTableRef" :data="tableData" border stripe style="width: 100%"
                    @selection-change="handleSelectionChange">
                    <el-table-column type="selection" style="background-color: #eee;" />
                    <el-table-column property="inCode" label="机构指标ID" header-align="center" align="center">
                    </el-table-column>
                    <el-table-column property="inOrganName" label="机构指标名称" header-align="center" align="center" />
                    <el-table-column property="inOrganUnit" label="指标单位" header-align="center" align="center" />
                    <el-table-column property="inOrganCeiling" label="参考上限" header-align="center" align="center" />
                    <el-table-column property="inOrganFloor" label="参考下限" header-align="center" align="center" />
                    <el-table-column property="ncode" label="对应指标标准" header-align="center" align="center" />
                    <el-table-column property="organName" label="所属机构" header-align="center" align="center" />
                    <el-table-column label="操作" width="180px" header-align="center" align="center">
                        <template #default="scope">
                            <el-button link type="success" size="small" style="padding: 0;color:#1ABC9C;"
                                @click="editClick(scope.row)">编辑</el-button>

                            <el-popconfirm title="确定要删除吗" @confirm="ondel(scope.row)">
                                <template #reference>
                                    <el-button link type="success" size="small" style="color: #1ABC9C;">删除</el-button>
                                </template>
                            </el-popconfirm>

                            <el-button link type="success" size="small" style="padding: 0;color:#1ABC9C"
                                @click="target_aim(scope.row)">指标映射</el-button>
                        </template>
                    </el-table-column>
                </el-table>
            </div>
            <!-- 分页 -->
            <div class="demo-pagination-block">
                <!-- <div class="demonstration">All combined</div> -->
                <el-pagination v-model:current-page="currentPage4" v-model:page-size="pageSize4"
                    :page-sizes="[5, 10, 15, 20]" :small="small" :disabled="disabled" :background="background"
                    layout="total, sizes, prev, pager, next, jumper" :total="total" @size-change="handleSizeChange"
                    @current-change="handleCurrentChange" />
            </div>
        </el-main>
    </el-container>
    <!-- 添加弹框 -->
    <div class="addDialog">
        <el-dialog v-model="dialogFormVisible" title="新增体检指标">
            <el-form :model="addData" style="height: 30rem; overflow-y: auto;">
                <div style="display: flex;justify-content:space-between;padding-right:15rem;padding-top:1rem;">
                    <el-form-item label="机构指标名称:" class="starColor">
                        <el-input v-model="addData.inOrganName" autocomplete="off" class="input-wh" placeholder="机构指标名称"
                            clearable />
                    </el-form-item>

                    <el-form-item label="体验机构:" class="starColor" style="margin-left: 2rem;">
                        <el-select v-model="addData.organId" placeholder="请选择" class="input-wh" @change="selectClick"
                            clearable>
                            <el-option v-for="item in itemArr" :key="item" :value="item.organId" :label="item.organName"
                                class="input-wh" />
                        </el-select>
                    </el-form-item>

                </div>
                <el-switch v-model="value" inactive-text="是否对比:" class="starColor" style="margin-left: 1.6rem;" />
                <el-form-item label="指标单位:" class="starColor starLeft">
                    <el-input v-model="addData.inOrganUnit" autocomplete="off" class="input-wh" clearable />
                </el-form-item>
                <el-form-item label="参考上限:" class="starColor starLeft">
                    <el-input v-model="addData.inOrganCeiling" autocomplete="off" class="input-wh" clearable />
                </el-form-item>
                <el-form-item label="参考下限:" class="starColor starLeft">
                    <el-input v-model="addData.inOrganFloor" autocomplete="off" class="input-wh" clearable />
                </el-form-item>
                <el-form-item label="正常提示:" class=" starText">
                    <el-input v-model="addData.inNormalPrompt" type="textarea" :rows="4" clearable />
                </el-form-item>
                <el-form-item label="偏高提示:" class=" starText">
                    <el-input v-model="addData.inHighPrompt" type="textarea" :rows="4" clearable />
                </el-form-item>
                <el-form-item label="偏低提示:" class=" starText">
                    <el-input v-model="addData.inLowPrompt" type="textarea" :rows="4" clearable />
                </el-form-item>
            </el-form>
            <template #footer>
                <span class="dialog-footer">
                    <el-button @click="dialogFormVisible = false">取消</el-button>
                    <el-button type="primary" @click="onAdd">确定</el-button>
                </span>
            </template>
        </el-dialog>
    </div>
    <!-- 编辑弹框 -->
    <div class="editDialog">
        <el-dialog v-model="editable" title="修改体检指标">
            <el-form :model="editData" style="height: 30rem; overflow-y: auto;">
                <div style="display: flex;justify-content:space-between;padding-right:15rem;padding-top:1rem;">
                    <el-form-item label="机构指标名称:" class="starColor">
                        <el-input v-model="editData.inOrganName" autocomplete="off" class="input-wh" />
                    </el-form-item>

                    <el-form-item label="体验机构:" class="starColor" style="margin-left: 2rem;">
                        <el-select v-model="editData.organId" placeholder="请选择机构" class="input-wh" @change="selectClick">
                            <el-option v-for="item in itemArr" :key="item" :value="item.organId" :label="item.organName"
                                class="input-wh" />
                        </el-select>
                    </el-form-item>
                </div>
                <el-switch v-model="value" inactive-text="是否对比:" class="starColor" style="margin-left: 1.6rem;" />
                <el-form-item label="指标单位:" class="starColor starLeft">
                    <el-input v-model="editData.inOrganUnit" autocomplete="off" class="input-wh" />
                </el-form-item>
                <el-form-item label="参考上限:" class="starColor starLeft">
                    <el-input v-model="editData.inOrganCeiling" autocomplete="off" class="input-wh" />
                </el-form-item>
                <el-form-item label="参考下限:" class="starColor starLeft">
                    <el-input v-model="editData.inOrganFloor" autocomplete="off" class="input-wh" />
                </el-form-item>
                <el-form-item label="正常提示:" class=" starText">
                    <el-input v-model="editData.inNormalPrompt" type="textarea" :rows="4" />
                </el-form-item>
                <el-form-item label="偏高提示:" class=" starText">
                    <el-input v-model="editData.inHighPrompt" type="textarea" :rows="4" />
                </el-form-item>
                <el-form-item label="偏低提示:" class=" starText">
                    <el-input v-model="editData.inLowPrompt" type="textarea" :rows="4" />
                </el-form-item>
            </el-form>
            <template #footer>
                <span class="dialog-footer">
                    <el-button @click="editable = false">取消</el-button>
                    <el-button type="primary" @click="onEdit">
                        确定
                    </el-button>
                </span>
            </template>
        </el-dialog>
    </div>
    <!-- 指标映射弹框 -->
    <el-dialog v-model="dialogFormVisibleA" title="指标映射">
        <el-form>
            <el-form :model="form" style="display:flex;
            flex-wrap: wrap;
            ">
                <el-form-item label="机构指标:" class="starColor">
                    <el-input v-model="form.option" placeholder="JGZB00001" disabled/>
                </el-form-item>

                <el-form-item label="标准指标:" class="starColor" style="margin-left: 2rem;">
                    <el-select v-model="form.ncode" placeholder="请选择" class="input-wh" @change="optionClick(form.ncode)">
                        <el-option v-for="item in tableDialog" :key="item" :value="item.ncode" class="input-wh" />
                    </el-select>
                </el-form-item>

            </el-form>
            <el-table :data="tableDialogArr" border style="width: 100%">
                <el-table-column prop="parameter" label="匹配参数" />
                <el-table-column prop="standAim" label="标准指标" />
                <el-table-column prop="organAim" label="机构指标" />
            </el-table>
        </el-form>
        <hr style="margin:2rem 0 0 0; color:#F2F2F2;">
        <template #footer style="background-color: #fff !important;">
            <span class="dialog-footer">
                <el-button @click="dialogFormVisibleA = false">取消</el-button>
                <el-button type="primary" @click="targetSure">
                    确定
                </el-button>
            </span>
        </template>
    </el-dialog>
</template>
<script lang="ts" setup>
import { ref, reactive, onMounted } from 'vue'
import { getOrgan, getOrganId, getTarget,updateById, editOrgan, addOrgan, delOrgan, delIdsOrgan } from './../apis/OrganTarget'
import zhCn from 'element-plus/dist/locale/zh-cn.mjs'
// import { ElMessage, ElMessageBox } from 'element-plus'
import 'element-plus/theme-chalk/el-loading.css';
import 'element-plus/theme-chalk/el-message.css';

// 分页
const locale = zhCn;//分页语言设置
const currentPage4 = ref(1)
const pageSize4 = ref(5)
const small = ref(false)
const background = ref(false)
const disabled = ref(false)
const editable = ref(false)
const deltable = ref(false)
const itemArr = reactive([])
let selectArr = reactive([])
//总条数
const total = ref(false)
const count = ref(5);
// const page = ref()
//弹框
let tableData = reactive<User[]>([])
const dialogFormVisible = ref(false)
const dialogFormVisibleA = ref(false)
const dialogFormVisibleB = ref(false)
const value = ref(true)//开关
const textarea = ref('')
const multipleSelection = ref<User[]>([])

const dialogVisible = ref(false)

interface User {
    inId: Number,
    inCode: string;
    organName: string;
    inOrganName: string;
    inOrganUnit: string;
    inOrganCeiling: string;
    inOrganFloor: string;
    ncode: string;
    inNormalPrompt: string;
    inHighPrompt: string;
    inLowPrompt: string;
}
const addData = reactive({
    inOrganName: "",
    inOrganUnit: "",
    inOrganCeiling: "",
    inOrganFloor: "",
    inNormalPrompt: "",
    inHighPrompt: "",
    inLowPrompt: "",
    organId: null
})
const editData = reactive({
    inId: Number,
    inCode: "",
    inOrganName: "",
    organId: "",
    inOrganUnit: "",
    inOrganCeiling: "",
    inOrganFloor: "",
    ncode: "",
    inNormalPrompt: "",
    inHighPrompt: "",
    inLowPrompt: ""
})

const deleData = reactive({
    inId: Number,
    inCode: "",
    inOrganName: "",
    organName: "",
    inOrganUnit: "",
    inOrganCeiling: "",
    inOrganFloor: "",
    ncode: "",
    inNormalPrompt: "",
    inHighPrompt: "",
    inLowPrompt: ""
})
//查询
const searchValue = reactive({
    organId: null,
    inOrganName: '',
    organ: '',
    type: '',
})
const searchValueArr=reactive(['searchValue.inOrganName',searchValue.organId])
//弹框表格
const tableDialog = reactive([])
const tableDialogArr = reactive([
    { id: 1, parameter: '指标名称', standAim: '', organAim: '机构指标' },
    { id: 1, parameter: '单位', standAim: '', organAim: '机构指标' },
    { id: 1, parameter: '参考上限', standAim: '', organAim: '机构指标' },
    { id: 1, parameter: '参考下限', standAim: '', organAim: '机构指标' },
    { id: 1, parameter: '正常提示', standAim: '', organAim: '' },
    { id: 1, parameter: '偏高提示', standAim: '', organAim: '' },
    { id: 1, parameter: '偏低提示', standAim: '', organAim: '' },

])
//表格渲染
const render = async () => {
    const { data } = await getOrgan({ page: currentPage4.value, limit: pageSize4.value, inOrganName: searchValue.inOrganName,organId:searchValue.organId })

    if (data.code == 0) {
        tableData.length = 0;
        tableData.push(...data.data.list);
        total.value = data.count

    }
    render()
}

//显示标准指标信息
let show_stand=()=>{
    let stand_arr = selectArr.filter(item => {
        return item.ncode === form.ncode
    })
    tableDialogArr.forEach((item)=>{
        item.standAim=''
    })
    // console.log(target_arr[0]);
    tableDialogArr[0].standAim = stand_arr[0].nname
    tableDialogArr[1].standAim = stand_arr[0].nunit
    tableDialogArr[2].standAim = stand_arr[0].nceiling
    tableDialogArr[3].standAim = stand_arr[0].nfloor
    tableDialogArr[4].standAim = stand_arr[0].nnormalPrompt
    tableDialogArr[5].standAim = stand_arr[0].nhighPrompt
    tableDialogArr[6].standAim = stand_arr[0].nlowPrompt
}

//点击指标映射按钮
let target_aim = (row) => {
    dialogFormVisibleA.value = true
    // console.log(tableData);
    // console.log(row.inId);
    let target_arr = tableData.filter(item => {
        return item.inId === row.inId;
    })
    // console.log(target_arr[0]);
    tableDialogArr[0].organAim = target_arr[0].inOrganName
    tableDialogArr[1].organAim = target_arr[0].inOrganUnit
    tableDialogArr[2].organAim = target_arr[0].inOrganCeiling
    tableDialogArr[3].organAim = target_arr[0].inOrganFloor

    form.option = target_arr[0].inCode
    
    form.ncode=row.ncode
    show_stand()
}

//体检机构
// 添加、编辑体检机构的下拉框数据显示(调用获取值的接口)
const add_selectinos = async () => {
    const { data } = await getOrganId();
    // console.log(data.data);
    if (data.code == 0) {
        itemArr.length = 0;
        data.data.forEach((v) => {
            if (!itemArr.includes(v.organName)) {
                itemArr.push(v);
            }
        });
    }
}

add_selectinos()//显示添加的下拉框数据

const selectClick = () => {//选择添加机构下拉框，触发这个事件，获取选择的值
    // console.log(addData.organName);
};

//指标映射渲染下拉框
const option_Click = async () => {
    const { data } = await getTarget();
    // console.log(data);

    if (data.code == 0) {

        data.data.forEach((v) => {
            if (!selectArr.includes(v.ncode)) {
                selectArr.push(v);
            }
        });
        tableDialog.length = 0;
        tableDialog.push(...data.data)

        //console.log(selectArr);
        //console.log(selectArr); // 过滤重复元素后的数组
    }
};
// 指标映射确定按钮
const targetSure=(ncode)=>{
    dialogFormVisibleA.value=false;
    // console.log(selectArr);
    let n_id=null
    let in_Id=null
    selectArr.forEach((item)=>{
        if(item.ncode==form.ncode){
            n_id=item.nid
        }
    })
    tableData.forEach((item)=>{
        if(item.inCode==form.option){
            in_Id=item.inId
        }
    })
    console.log(tableData);
    updateById({inId:in_Id,nid:n_id}).then((res)=>{
        res.data.code==0?render():ElMessage.error('指标匹配失败');
    })
    
    
}
option_Click()
let optionClick = (ncode) => {
    show_stand()
    console.log(selectArr);
    
}
const editClick = (row: any) => {
    // console.log(row.organName);
    console.log(itemArr);
    itemArr.forEach(item => {
        if (item.organName == row.organName) {
            editData.organId = item.organId
        }
    })
    editable.value = true;
    editData.inCode = row.inCode;
    editData.inId = row.inId;
    editData.inOrganName = row.inOrganName;
    editData.inOrganUnit = row.inOrganUnit
    editData.inOrganCeiling = row.inOrganCeiling
    editData.inOrganFloor = row.inOrganFloor
    editData.ncode = row.ncode

}
//删除
const ondel = async (row) => {

    const { data } = await delOrgan(row.inId)
    console.log(data);
    
    if (data.code == 0) {
        tableData = tableData.filter(item => item.inId !== row.inId);
        total.value = data.total;
        ElMessage.success('删除成功');
        render()
    }
    console.log(row.inId);

}
// 批量删除
let delArry = []
const delLot = (v) => {
    dialogVisible.value = true
    for (let i = 0; i < multipleSelection.value.length; i++) {
        delArry.push(multipleSelection.value[i].inId)
        let arr = Object.values(delArry)
        delArry = arr
    }
    render()

    if (multipleSelection.value.length > 0) {
        ElMessageBox.confirm(
            '是否确定删除数据?',
            '确认提示',
            {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'warning',
            }
        )
            .then(() => {
                deleteData(); // 调用删除函数
                render();
                ElMessage({
                    type: 'success',
                    message: '删除成功'
                })
            })
            .catch(() => {
                ElMessage({
                    type: 'info',
                    message: '删除已取消',
                });
            });
    } else {
        ElMessageBox.confirm(
            '你没有选择任何数据，请选择一行数据',
            '确认提示',
            {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'warning',
            }
        )
    }

}

const deleteData = async (v) => {
    const { data } = await delIdsOrgan(delArry)
    console.log(data);

    if (data.code == 0) {
        render()
        ElMessage.success('删除成功');
    } else {
        ElMessage.error('删除失败');
    }
};
const handleSizeChange = (val: number) => {
    pageSize4.value = val
    render()
}
const handleCurrentChange = (val: number) => {
    currentPage4.value = val
    render();
}
//查询
const onSubmit = () => {
    
    render()
    console.log('查询成功!')
}
//重置
const onReset = () => {
    console.log('重置成功');
    searchValue.inOrganName = '';
    searchValue.organId='';
    searchValue.type='';
    currentPage4.value = 1;
    render()

}

//添加
const onAdd = async () => {
    const { data } = await addOrgan(addData);
    console.log(data);

    if (data.code == 0) {
        dialogFormVisible.value = false;
        addData.inOrganName = '';
        addData.organId = null;
        addData.inOrganUnit = '';
        addData.inOrganCeiling = '';
        addData.inOrganFloor = '';
        addData.inNormalPrompt = '';
        addData.inHighPrompt = '';
        addData.inLowPrompt = '';
        ElMessage.success('添加成功');
    }
    //console.log(data);
    await render()
}
onMounted(render)
//编辑
const onEdit = async () => {
    const { data } = await editOrgan(editData);
    if (data.code == 0) {
        editData.organId = '';
        editable.value = false;
        ElMessage.success('编辑成功');
        render()
    }

}
// 表格
const handleSelectionChange = (val: User[]) => {
    multipleSelection.value = val
}
//指标映射
const form = reactive({
    nid: null,
    ncode: '',
    option: ''
})
</script>

<style lang="less" scoped>
.el-container {
    height: calc(100% - 4rem);
}

.elHeader {
    background-color: #fff;
    padding: 0;
    margin: 0 1rem 0 1rem;
    display: flex;
    align-items: center;

    div {
        margin-left: 1rem;
        margin-top: 0.5rem;
        font-size: 2rem;
    }
}

.el-main {
    padding: 0;
    position: relative;
}

.pick {
    border: 1px solid #ccc;
    margin: 0 1rem 0 1rem;

    h4 {
        padding-left: 1rem;
    }

    .pick-form {
        display: flex;
        justify-content: space-between;
        border-top: 1px solid #ccc;
        padding-top: 1.5rem;
        padding-left: 1rem;
    }
}

.pick-btn {
    margin-left: 2rem;
    margin-top: 1rem;

    .el-message-box__container {
        background-color: #fff;
    }
}

.pick-table {
    margin: 1.3rem 1rem 0 2rem;
}


:deep(.editDialog) {
    .el-dialog {
        width: 60rem;
        height: 30rem;

        .el-dialog__header {
            height: 4rem;
            background-color: #eee;
            margin: 0;
            padding: 0;
            line-height: 4.5rem;

            .el-dialog__title {
                margin-left: 2rem;
            }
        }

        .el-dialog__footer {
            padding: 1rem 3rem;
            background-color: #fff;
            border-top: 1px solid #ccc;
        }

        .el-dialog__body {
            padding: 0 !important;
            background-color: #fff;
        }
    }
}

:deep(.addDialog) {
    .el-dialog {
        width: 60rem;
        height: 30rem;

        .el-dialog__header {
            height: 4rem;
            background-color: #eee;
            margin: 0;
            padding: 0;
            line-height: 4.5rem;

            .el-dialog__title {
                margin-left: 2rem;
            }
        }

        .el-dialog__footer {
            padding: 1rem 3rem;
            background-color: #fff;
            border-top: 1px solid #ccc;
        }

        .el-dialog__body {
            padding: 0 !important;
            background-color: #fff;
        }

    }
}

.demo-pagination-block {
    display: flex;
    justify-content: end;
    margin-top: 2rem;
    margin-right: 1rem;

    :deep(.el-pager li.is-active) {
        color: #1ABC9C;
    }

    :deep(.el-pager li:hover) {
        color: #1ABC9C;

    }

    :deep(.el-pagination button:hover) {
        color: #1ABC9C;
    }
}


.starColor::before {
    content: "*";
    color: red;
    padding-top: 0.5rem;
}

.starLeft {
    margin: 1rem 0 0 1.4rem;
}

.starText {
    margin: 1rem 3rem 0 1.8rem;
    width: 38rem;
    height: 6rem;
}

.input-wh {
    width: 13rem;
    height: 1.8rem;
}



.el-dialog__header {
    background-color: #F2F2F2;
}

.tableSpace {
    padding: 0 2rem;
}
</style>